package com.enjoyor.soa.traffic.core.tpcms.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.enjoyor.soa.traffic.api.dto.tpcms.PassCardDto;
import com.enjoyor.soa.traffic.api.dto.tpcms.PassVehicleFileDto;
import com.enjoyor.soa.traffic.core.tpcms.domain.InfoAlarmRedis;
import com.enjoyor.soa.traffic.core.tpcms.domain.PassCard;
import com.enjoyor.soa.traffic.core.tpcms.mapper.IPassCardMapper;
import com.enjoyor.soa.traffic.core.tpcms.mapper.IPassVehicleFileMapper;
import com.enjoyor.soa.traffic.core.tpcms.service.IPassCardService;
import com.enjoyor.soa.traffic.frame.logger.IPubLogMapper;
import com.enjoyor.soa.traffic.frame.support.redis.IRedisTool;
import com.enjoyor.soa.traffic.util.enums.EnumApplyStatus;
import com.enjoyor.soa.traffic.util.enums.log.LogInfoDic;
import com.enjoyor.soa.traffic.util.helper.JsonHelper;
import com.enjoyor.soa.traffic.util.helper.ReflectHelper;
import com.enjoyor.soa.traffic.util.helper.TimeHelper;
import com.enjoyor.soa.traffic.util.pojo.Page;

/**
 * 通行证管理信息
 * 
 * @author fzj 2018年5月8日
 */
@Service
@Transactional
public class PassCardService implements IPassCardService {

    @Autowired
    private IPassCardMapper passCardMapper;

    @Autowired
    private IPassVehicleFileMapper passVehicleFileMapper;

    @Autowired
    private IPubLogMapper pubLogMapper;

    @Autowired
    private IRedisTool redisTool;

    @Value("${log.system.name}")
    private String systemName;

    /**
     * 申请单审核
     */
    @Override
    public String insertPassCard(PassCardDto passCardDto, String userName) {
        // 默认申请信息
        String passCardId = "P" + TimeHelper.getUniqueString();
        passCardDto.setPassCardId(passCardId);
        PassCard passCardPojo = ReflectHelper.beanToBean(passCardDto, PassCard.class);
        passCardMapper.insert(passCardPojo);
        // 保存日志
        pubLogMapper.saveNoramlLogInfo(userName, systemName, LogInfoDic.LOG_TRANSTYPE_ENUM.TRANSTYPE_INSERT.getCode(),
                String.format("生成通行证编号:{%s} 操作成功!", new Object[] { passCardId }),
                LogInfoDic.LOG_MODULAR_ENUM.PACC_CHECK_MANAGEMENT.getMessage());
        return passCardId;
    }

    /**
     * 删除通行证
     */
    @SuppressWarnings("unused")
    public int deletePassCard(String passCardId, String userName) {
        // 查询通行证信息
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("passCardId", passCardId);
        List<PassCard> passCardList = passCardMapper.getPassCardList(map);

        PassCard passCardPojo = new PassCard();
        passCardPojo.setPassCardId(passCardId);
        passCardPojo.setIsDelete("1");
        int deleteNum = passCardMapper.updateByIdSelective(passCardPojo);

        // 移除redis
        if (passCardList.size() > 0) {
            String licenseNumber = passCardList.get(0).getLicenseNumber();
            Boolean redisDelete = redisTool.del(licenseNumber);
            // infoAlarmRedisMapper.deleteRedisByVehicle(licenseNumber);
        }
        // 保存日志
        pubLogMapper.saveNoramlLogInfo(userName, systemName, LogInfoDic.LOG_TRANSTYPE_ENUM.TRANSTYPE_DELETE.getCode(),
                String.format("删除通行证编号:{%s} 操作成功!", new Object[] { passCardId }),
                LogInfoDic.LOG_MODULAR_ENUM.PACC_CHECK_MANAGEMENT.getMessage());
        return deleteNum;
    };

    /**
     * 修改通行证状态-延期、打印
     */
    public int editPassCardStatus(String passCardId, String passStatusId, String extensionPeople, String isSelf,
            String extensionDays, String userName) {
        PassCard passCardPojo = new PassCard();
        passCardPojo.setPassCardId(passCardId);
        passCardPojo.setPassStatusId(passStatusId);
        int editNum = 0;
        if (EnumApplyStatus.UNPRINT.getKey().equals(passStatusId)) {
            passCardPojo.setPassStatusName(EnumApplyStatus.UNPRINT.getValue());
            editNum = passCardMapper.updateByIdSelective(passCardPojo);
        } else if (EnumApplyStatus.ISPRINT.getKey().equals(passStatusId)) {
            passCardPojo.setPassStatusName(EnumApplyStatus.ISPRINT.getValue());
            editNum = passCardMapper.updateByIdSelective(passCardPojo);
        } else if (EnumApplyStatus.ISEXTENSION.getKey().equals(passStatusId)) {
            passCardPojo.setPassStatusName(EnumApplyStatus.ISEXTENSION.getValue());
            passCardPojo.setExtensionPeople(extensionPeople);
            passCardPojo.setIsSelf(isSelf);
            passCardPojo.setExtensionDays(extensionDays);
            editNum = passCardMapper.updateByIdSelective(passCardPojo);

            // 存储redis
            this.setRedisByCard(passCardId);
        } else if (EnumApplyStatus.ISLOSE.getKey().equals(passStatusId)) {
            passCardPojo.setPassStatusName(EnumApplyStatus.ISPRINT.getValue());
            editNum = passCardMapper.updateByIdSelective(passCardPojo);
        }
        // 保存日志
        pubLogMapper.saveNoramlLogInfo(userName, systemName, LogInfoDic.LOG_TRANSTYPE_ENUM.TRANSTYPE_UPDATE.getCode(),
                String.format("修改通行证编号:{%s} 操作成功!", new Object[] { passCardId }),
                LogInfoDic.LOG_MODULAR_ENUM.PACC_CHECK_MANAGEMENT.getMessage());
        return editNum;
    }

    /**
     * 查询通行证列表信息
     */
    @Override
    public List<PassCardDto> getPassCardList(Map<String, Object> map) {
        // 获取通行证基础信息
        List<PassCardDto> passCardDtoList = passCardMapper.getPassCardDetailList(map);
        // List<PassCardDto> passCardDtoList =
        // ReflectHelper.listToList(passCardList, PassCardDto.class);
        for (PassCardDto passCardDto : passCardDtoList) {
            // String passApplyId = passCardDto.getPassApplyId();
            String applyVehicleId = passCardDto.getApplyVehicleId();
            // PassApply passApply = passApplyMapper.selectById(passApplyId);
            // passCardDto = ReflectHelper.beanToBean(passApply,
            // PassCardDto.class);
            Map<String, Object> fileMap = new HashMap<String, Object>();
            fileMap.put("applyVehicleId", applyVehicleId);
            List<PassVehicleFileDto> fileList = ReflectHelper.listToList(passVehicleFileMapper.getFileList(fileMap),
                    PassVehicleFileDto.class);
            passCardDto.setVehicleFiles(fileList);
        }
        return passCardDtoList;
    }

    /**
     * 查询当年通行证最大编号
     */
    @Override
    public String getMaxPassCardId() {
        String maxPassCardId = "";
        PassCard passCard = passCardMapper.getMaxPassCardId();
        if (passCard != null && passCard.getPassCardId() != null) {
            maxPassCardId = passCard.getPassCardId();
        } else {
            String year = TimeHelper.dateToString(new Date(), "yyyy");
            maxPassCardId = year + "P0100";
        }
        return maxPassCardId;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public Page getPassCardPage(Page page) {
        return passCardMapper.selectPageInfo(page);
    }

    /**
     * 根据通行证存储redis
     * 
     * @param passCardId
     *            通行证编号
     */
    private Boolean setRedisByCard(String passCardId) {
        Boolean redisResult = false;
        // 获取通行证基础信息
        Map<String, Object> cardMap = new HashMap<String, Object>();
        cardMap.put("passCardId", passCardId);
        List<PassCardDto> passCardDtoList = passCardMapper.getPassCardDetailList(cardMap);
        if (passCardDtoList.size() > 0) {
            try {
                String key = passCardDtoList.get(0).getLicenseNumber();
                String loseEffectDate = passCardDtoList.get(0).getLoseEffectDate();
                String redisValueJson = redisTool.get(key);
                if (redisValueJson != null && redisValueJson != "") {
                    InfoAlarmRedis redisValue = (InfoAlarmRedis) JsonHelper.jsonToObject(redisValueJson,
                            InfoAlarmRedis.class);
                    redisValue.setLoseEffectDate(loseEffectDate);
                    redisResult = redisTool.setObject(key, redisValue);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return redisResult;
    }

}
